<template>
  <!--
    只有 List 在可视范围内才会检查滚动位置触发 onLoad
   -->
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="已显示全部评论"
    :error="error"
    error-text="加载失败，请点击重试"
    @load="onLoad"
  >
    <CommentItem
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @information="$emit('information', $event)"
    ></CommentItem>
  </van-list>
</template>

<script>
import CommentItem from './CommentItem'
import { getComments } from '@/api/comment'
export default {
  name: 'CommentList',
  props: {
    art_id: {
      type: String,
      required: true
    },
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: 'a'
    }
  },
  created() {
    console.log(this.art_id, 'qwert')
  },
  components: {
    CommentItem
  },
  data() {
    return {
      loading: false,
      finished: false,
      offset: null, // 获取下一页数据的标记
      error: false
    }
  },
  methods: {
    async onLoad() {
      console.log(this.list, 'this.list')
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        console.log(this.art_id, 'this.art_id')
        const { data } = await getComments({
          type: this.type,
          source: this.art_id,
          offset: this.offset
        })
        this.offset = data.last_id
        this.list.push(...data.results)
        console.log(this.list)
        // 加载状态结束
        this.loading = false
        if (!data.results.length) {
          this.finished = true
        }
      } catch (error) {
        this.loading = false
        this.error = true
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
